<template>
  <div class="search">
    <Row :gutter="16" class="all-height">
      <Col :span="showRight ? 18 : 24" class="all-height">
        <Card class="all-height card-child-height">
          <div style="display: flex; justify-content: space-between; align-items: center; height: 40px">
            <div style="display: flex; flex-wrap: nowrap; overflow-x: auto">
              <Button @click="handleReset" icon="md-refresh">刷新</Button>
              <Button @click="pushBatch" type="primary">批量入库</Button>
              <Button @click="batchDel"  >批量删除 </Button>
              <Button  @click="dropExportData">导出所选数据</Button>
              <Button :loading="importing1"  @click="dropExportAll">导出全部数据</Button>
            </div>
            <Col span="2" style="text-align: right">
              <Icon
                  color="#fff"
                  style="background: rgb(45, 154, 244); border-radius: 50%; padding: 3px"
                  :type="!showRight ? `ios-arrow-back` : `ios-arrow-forward`"
                  @click.native="clickShowRight"
              ></Icon>
            </Col>
          </div>
          <div class="mt-12" style="height: 40px" v-show="openTip">
            <Alert show-icon>
              已选择
              <span class="select-count">{{ selectList.length }}</span>
              项
              <a class="select-clear" @click="clearSelectAll">清空</a>
            </Alert>
          </div>

          <div class="mt-12" style="height: calc(100% - 104px)">
            <div class="tableContainer ">
              <div v-if="loading" class="wh-100 d-flex-around-center">
                <Spin></Spin>
              </div>
              <div v-else v-ref-height="abca" class="wh-100">
                <el-table v-if="data.length > 0" :loading="listLoading" ref="table" :height="abca.value" :data="data"
                          empty-text="暂无数据"
                          border @selection-change="handleSelectionChange" style="width: 100%">
                  <el-table-column type="selection" :width="tableWidth"></el-table-column>
                  <el-table-column type="index" label="序号" :width="tableWidth"></el-table-column>
                  <el-table-column prop="name" label="单位名称"></el-table-column>
                  <el-table-column prop="status" label="经营状态">
                    <template slot-scope="scope">
                      <span v-if="scope.row.status === 0">正常</span>
                      <span v-if="scope.row.status === 1">吊销</span>
                      <span v-if="scope.row.status === 2">注销</span>
                      <span v-if="scope.row.status === 3">其他</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="code" label="统一社会信息代码" width="160"></el-table-column>
                  <el-table-column prop="nature" label="单位性质" width="180">
                    <template slot-scope="scope">
                      {{ getUnitNature(scope.row.nature) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="industry" label="单位行业">
                    <template slot-scope="scope">
                      {{ getUnitIndustry(scope.row.industry) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="address" label="单位所在地代码"></el-table-column>
                  <el-table-column prop="contactPerson" label="单位联系人"></el-table-column>
                  <el-table-column prop="contactPhone" label="联系电话" width="120"></el-table-column>
                  <el-table-column prop="location" label="单位所在地" width="200"></el-table-column>
                  <el-table-column prop="sourceType" label="数据来源" width="160">
                    <template slot-scope="scope">
                      <span v-if="scope.row.sourceType === 0">学校审核通过存入</span>
                      <span v-if="scope.row.sourceType === 1">双选会审核通过存入</span>
                      <span v-if="scope.row.sourceType === 2">统计系统存入</span>
                    </template>
                  </el-table-column>
                  <el-table-column fixed="right" label="操作">
                    <template slot-scope="scope">
                      <el-button type="text" size="small" @click="remove(scope.row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <div v-else class="wh-100">
                  <NoData class="wh-100"></NoData>
                </div>
              </div>
            </div>

            <div class="d-flex-center" style="height: 100px">
              <Page
                  :current="searchForm.pageNumber"
                  :total="total"
                  :page-size="searchForm.pageSize"
                  @on-change="changePage"
                  @on-page-size-change="changePageSize"
                  :page-size-opts="[10, 20, 50]"
                  size="small"
                  show-total
                  show-elevator
                  show-sizer
              ></Page>
            </div>

          </div>
        </Card>
      </Col>
      <Col span="6" class="all-height" v-show="showRight">
        <Card class="all-height card-child-height">
          <Row v-show="openSearch" @keydown.enter.native="handleSearchB">
            <Col span="24">
              <div class="drawer-header">
                <div style="margin-right: 16px">查询区</div>
              </div>
            </Col>
            <Col span="24">
              <Form ref="searchForm" :model="searchForm" :label-width="labelWidth" class="marginForm">
                <FormItem label="单位名称">
                  <Input type="text" v-model="searchForm.name" clearable placeholder="请输入单位名称"
                         style="width: 100%"
                         @click.prevent="$event.preventDefault()" />
                </FormItem>
                <FormItem label="经营状态">
                  <Select v-model="searchForm.status" clearable
                          style="width: 100%">
                    <Option v-for="item in statusList" :value="item.value" :key="item.value">{{ item.label }}</Option>
                  </Select>
                </FormItem>
                <FormItem label="统一社会信用代码">
                  <Input type="text" v-model="searchForm.code" clearable placeholder="请输入统一社会信用代码"
                         style="width: 100%"
                         @click.prevent="$event.preventDefault()" />
                </FormItem>
                <FormItem label="单位性质">
                  <Select v-model="searchForm.nature" clearable style="width: 100%">
                    <Option v-for="(item,index) in unitNatureDicts" :value="item.value" :key="index">{{ item.title }}
                    </Option>
                  </Select>
                </FormItem>
                <FormItem label="单位行业">
                  <Select v-model="searchForm.industry" clearable
                          style="width: 100%">
                    <Option v-for="(item,index) in unitIndustryDicts" :value="item.value" :key="index">{{ item.title }}
                    </Option>
                  </Select>
                </FormItem>
                <FormItem label="单位联系人">
                  <Input type="text" v-model="searchForm.contactPerson" clearable placeholder="请输入单位联系人"
                         style="width: 100%"
                         @click.prevent="$event.preventDefault()" />
                </FormItem>
                <FormItem label="单位联系人电话">
                  <Input type="text" v-model="searchForm.contactPhone" clearable placeholder="请输入单位联系人电话"
                         style="width: 100%"
                         @click.prevent="$event.preventDefault()" />
                </FormItem>
                <FormItem label="单位所在地">
                  <el-cascader
                      clearable
                      class="w-100"
                      v-model="searchForm.houseTransferLocationCode"
                      :options="locationOfTheUnitList"
                      :props="provincesAndMunicipalitiesProps"
                      @change="changeCar"
                  ></el-cascader>
                </FormItem>

                <FormItem class="br mt-12 mb-12 box-key">
                  <Button @click="handleSearchB" type="primary" icon="ios-search">搜索</Button>
                  <Button @click="handleReset">重置</Button>
                </FormItem>
              </Form>
            </Col>
          </Row>

        </Card>
      </Col>
    </Row>
    <Modal
        v-model="importFormView"
        title="导入用人单位信息">
      <Form :model="importForm" :label-width="80">
        <FormItem label="文件: ">
          <Upload
              accept=".xls,.xlsx"
              :before-upload="handleUpload">
            <Button icon="ios-cloud-upload-outline">点击上传</Button>
          </Upload>
        </FormItem>
        <FormItem label=" ">
          <div v-if="importForm.file !== null">
            {{ importForm.file.name }}
          </div>
          <div>说明：请依据模板数据格式导入，文件格式必须为.xlsx</div>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="importFormcCncel">取消</Button>
        <Button type="primary" :loading="importing" @click="importFormOk">开始上传</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import {
  companiesUpdateAPI,
  companiesAddAPI,
  exportAll
} from '@/api/bys/companies/index';
import addEdit from './addEdit.vue';
import Cookies from 'js-cookie';
import NoData from '@/components/NoData.vue';
import { getDictDataByType } from '@/api';
import {
  companyAwaitDeleteAPI,
  companyAwaitPageAPI,
  companyAwaitPushAPI,
  exportAllBysXjInfo,
  exportBatchMarketDataAPI
} from '@/api/bys/companies/await';
import { newProvincialDataApi } from '@/api/bys';

export default {
  name: 'bysXjCompare',
  components: {
    addEdit,
    NoData
  },
  data() {
    return {
      importFormView: false,
      importing: false,
      importForm: {
        file: null,
        importMode: '1'
      },
      listLoading: false,
      tableWidth: 60,
      labelWidth: 110,
      resource: '',
      abca: { value: 0 },
      cardId: '',
      status: '',
      bysId: '',
      height1: 0,
      openSearch: true,
      showRight: true,
      openTip: true, // 显示提示
      showType: '0', // 添加或编辑标识
      showDrawer: false, // 显示添加编辑抽屉
      loading: false, // 表单加载状态
      searchForm: {
        // 搜索框初始化对象
        pageNumber: 1, // 当前页数
        pageSize: 20, // 页面大小
        'code': '',
        'industry': '',
        'name': '',
        'nature': '',
        status: '',
        address: '',
        contactPerson: '',
        contactPhone: '',
      },
      selectList: [], // 多选数据
      form: {},
      statusList: [
        { value: '0', label: '正常' },
        { value: '1', label: '吊销' },
        { value: '2', label: '注销' },
        { value: '3', label: '其他' }
      ],
      unitNatureDicts: [],
      unitIndustryDicts: [],
      data: [], // 表单数据
      pageNumber: 1, // 当前页数
      pageSize: 10, // 页面大小
      total: 0, // 表单数据总数
      locationOfTheUnitList:[],//单位所在地
      provincesAndMunicipalitiesProps: {
        label: 'name',
        value: 'code',
        children: 'children'
      },
    };
  },
  methods: {

    //导出全部数据
    dropExportAll() {
      this.importing1 = true;
      let params ={
        "code": this.searchForm.code,
        "industry": this.searchForm.industry,
        "name":this.searchForm.name,
        "nature": this.searchForm.nature,
        "pageNo": this.searchForm.pageNumber,
        "pageSize": this.searchForm.pageSize,
        "status": this.searchForm.status,
      }

      exportAllBysXjInfo(params).then(res => {
        this.importing1 = false;
        // type的格式可以可以设置，可以把appcation/json设置进去，然后设置导出的类型
        const blob = new Blob([res], {type: 'charset=utf-8'});
        let url = window.URL.createObjectURL(blob);

        const link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', '基础本信息.xlsx');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link); // 删除节点
        window.URL.revokeObjectURL(url); //释放该 url
      });
    },


    newObtainTheCascadingDataOfProvincesAndCities(){
      newProvincialDataApi().then((res) =>{
        this.locationOfTheUnitList = res.result;
        console.log("this.locationOfTheUnitList",this.locationOfTheUnitList)
      })
    },
    changeCar(){
      this.searchForm.address = this.searchForm.houseTransferLocationCode[2];
    },
    //导出所选数据
    dropExportData() {
      let ids = ''
      if (this.selectList.length <= 0) {
        this.$Message.warning('您还未选择要导出的数据');
        return;
      } else {
        ids = this.selectList.map((obj) => {
          return obj.id
        }).join(",");
        exportBatchMarketDataAPI({ids }).then((res) => {
          // type的格式可以可以设置，可以把appcation/json设置进去，然后设置导出的类型
          const blob = new Blob([res], {type: 'charset=utf-8'});
          let url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.style.display = 'none';
          link.href = url;
          link.setAttribute('download', '市场信息.xlsx');
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link); // 删除节点
          window.URL.revokeObjectURL(url); //释放该 url
        })
      }
    },
    
    getUnitNature(index) {
      let val = '';
      this.unitNatureDicts.map(item => {
        if (index == item.value) {
          val = item.title;
        }
      });
      return val;
    },
    getUnitIndustry(index) {
      let val = '';
      this.unitIndustryDicts.map(item => {
        if (index == item.value) {
          val = item.title;
        }
      });
      return val;
    },
    async getDictData() {
      //单位性质
      await getDictDataByType('unit-nature').then(res => {
        if (res.success) {
          this.unitNatureDicts = res.result;
        }
      });
      // 单位行业
      await getDictDataByType('unit-industry').then(res => {
        if (res.success) {
          this.unitIndustryDicts = res.result;
        }
      });
    },
    handleSelectionChange(val) {
      this.selectList = val;
    },
    init() {
      this.getDataListB();
      this.openSearch = true;
    },
    // 显示隐藏右侧区域
    clickShowRight() {
      this.showRight = !this.showRight;
    },
    handleSearchB() {
      this.getDataListB();
    },
    changePage(v) {
      this.searchForm.pageNumber = v;
      this.getDataListB();
      this.clearSelectAll();
    },
    changePageSize(v) {
      this.searchForm.pageSize = v;
      this.getDataListB();
    },

    handleReset() {
      this.searchForm = {
        // 搜索框初始化对象
        pageNumber: 1, // 当前页数
        pageSize: 20, // 页面大小
        'code': '',
        'industry': '',
        'name': '',
        'nature': '',
        status: ''
      };
      this.$refs.searchForm.resetFields();
      this.getDataListB();
    },

    clearSelectAll() {
      this.$refs.table.clearSelection(false);
    },
    downloadTemple() {
      window.location.href = process.env.BASE_URL + '标准单位库导入模板.xlsx';
    },
    importFormOk() {
      if (this.importForm.file == null) {
        this.$Message.info('请选择文件');
        return;
      }
      let formData = new FormData();
      formData.append('file', this.importForm.file);
      this.importing = true;
      formData.append('file', this.importForm.file);
      this.importing = true;
      exportAll(formData).then(res => {
        if (res.code === 200) {
          // this.$message.success("导入开始，请前往导入历史查看导入结果信息")
          this.importing = false;
          this.importFormView = false;
          this.tipMessage = '导入正在进行，点击此处或关闭弹窗点击导入历史按钮查看导入结果信息';
          this.type = 'success';
          this.importPromptVisible = true;
          this.$message.success('导入成功');
          this.handleSearchB();
        }
      });
    },

    importFormcCncel() {
      this.importForm.file = null;
      this.importFormView = false;
    },
    handleUpload(file) {
      const fileExt = file.name.split('.').pop().toLocaleLowerCase();
      if (!(fileExt == 'xlsx' || fileExt == 'xls')) {
        this.$Notice.warning({
          title: '文件类型错误',
          desc:
              '所选文件‘ ' +
              file.name +
              ' ’不是EXCEL文件，请选择后缀为.xlsx或者.xls的文件。'
        });
      } else {
        this.importForm.file = file;
      }
      // this.importForm.file = file;
      return false;
    },
    getDataListB() {
      this.listLoading = true;
      companyAwaitPageAPI({...this.searchForm})
          .then(res => {
            this.listLoading = false;
            if (res.success) {
              this.loading = false;
              this.data = res?.result?.records || [];
              this.total = res?.result?.total || 0;
            }
          })
          .finally(() => {
            this.loading = false;
          });
    },
    submit(data, type) {
      this.loading = true;
      let address = '';
      if (data.address && data.address.length > 0) {
        address = data.address[data.address.length - 1];
      }
      data.address = address;
      if (type == 2) {
        delete data.id;
        companiesAddAPI(data).then(res => {
          if (res.code == 200) {
            this.$message.success('添加成功');
            this.handleReset();
          } else {
            this.$message.error(res.message);
            this.handleReset();
          }
        });
      } else if (type == 1) {
        let params = {
          'address': data.address,
          'code': data.code,
          'contactPerson': data.contactPerson,
          'contactPhone': data.contactPhone,
          'id': data.id,
          'industry': data.industry,
          'location': data.location,
          'name': data.name,
          'nature': data.nature,
          'status': data.status
        };
        companiesUpdateAPI(params).then(res => {
          if (res.code == 200) {
            this.$message.success('编辑成功');
            this.handleReset();
          } else {
            this.$message.error(res.message);
            this.handleReset();
          }
        });
      }
    },
    remove(v) {
      let that = this
      this.$Modal.confirm({
        title: '确认删除',
        // 记得确认修改此处
        content: '您确认要删除该条数据?',
        loading: true,
        onOk: () => {
          // 删除
          that.delectData({ idList: v.id })
        }
      });
    },
    batchDel(){
      let idList='',that = this
      console.log(this.selectList);
      if (this.selectList.length  < 1) {
        this.$Message.warning('您还未选择要导出的数据');
        return;
      } else {
        idList = this.selectList.map((obj) => {
          return obj.id
        }).join(",");
        that.delectData({ idList  })

      }
    },
    delectData(data){
      companyAwaitDeleteAPI().then(res => {
        this.$Modal.remove();
        if (res.success) {
          this.$Message.success('操作成功');
          this.getDataListB();
        }
      });
    },
    pushBatch() {
      let ids=''
      if (this.selectList.length <= 0) {
        this.$Message.warning('您还未选择要导出的数据');
        return;
      } else {
        ids = this.selectList.map((obj) => {
          return obj.id
        }).join(",");
        companyAwaitPushAPI({ids  }).then((res) => {
          // type的格式可以可以设置，可以把appcation/json设置进去，然后设置导出的类型
         if (res.code == 200){
           this.getDataListB()
           this.$Message.success('入库成功')
         }else {
           this.$Message.error(res.message)
         }
        })
      }

    },
    onRestWindow() {
      this.labelWidth = this.searchLabelWidth(110);
      this.tableWidth = this.searchLabelWidth(60);
    }
  },
  async mounted() {
    await this.getDictData();
    await this.newObtainTheCascadingDataOfProvincesAndCities()
    this.onRestWindow();
    window.addEventListener('resize', this.onRestWindow);
    let resource = JSON.parse(Cookies.get('userInfo')).resource;
    this.resource = resource;
    this.init();

  },
  beforeDestroy() {
    window.removeEventListener('resize', this.onRestWindow);
  }
};
</script>
<style lang="less">
// 建议引入通用样式 具体路径自行修改 可删除下面样式代码
@import '../../../../styles/table-common.less';
@import '../../../personInfo.less';

.tableContainer {
  width: 100%;
  height: calc(100% - 100px);
}

.search {
  .operation {
    margin-bottom: 2vh;
  }

  .select-count {
    font-weight: 600;
    color: #40a9ff;
  }

  .select-clear {
    margin-left: 10px;
  }

  .page {
    margin-top: 2vh;
  }

  .drop-down {
    margin-left: 5px;
  }
}

.all-height {
  height: 100%;
}
</style>
<style lang="less" scoped>
// 重构样式
/deep/ .ivu-form-item-label {
  display: flex;
  justify-content: right;
  width: 150px !important;
}

/deep/ .ivu-form-item {
  width: 100%;
  margin-bottom: 0.1rem;
  margin-right: 0 !important;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

/deep/ .ivu-form-item-content {
  width: 100% !important;
  margin-left: 0 ! important;
}

/deep/ .ivu-select {
  width: 100% !important;
}

/deep/ .ivu-date-picker {
  width: 100% !important;
}

/deep/ .br {
  margin-top: 15px;
  bottom: -8px !important;

  .ivu-form-item-content {
    display: flex;
  }
}

.box-key {
  /deep/ .ivu-form-item-content {
    margin-left: 102px !important;
  }
}
</style>
